package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.OrderTO;
import com.atguigu.common.to.SeckillOrderTO;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVO;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.common.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {


    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    WmsFeignService wmsFeignService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    StringRedisTemplate redisTemplate;
    private ThreadLocal<OrderSubmitVO> submitVOThreadLocal = new ThreadLocal<>();
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVO confirmOrder() {
        OrderConfirmVO orderConfirmVO = new OrderConfirmVO();
        MemberRespVO memberRespVO = LoginUserInterceptor.threadLocal.get();
        //获取主线程的request上下文
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //子线程共享主线程的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询用户所有收获地址列表
            List<MemberAddressVO> address = memberFeignService.getAddress(memberRespVO.getId());
            orderConfirmVO.setAddress(address);
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //子线程共享主线程的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询购物车中所有选中的购物项
            List<OrderItemVO> items = cartFeignService.getCurrentUserCartItems();
            orderConfirmVO.setItems(items);
            //计算订单总额
            BigDecimal sum = BigDecimal.ZERO;
            if (items != null && !items.isEmpty()) {
                for (OrderItemVO item : items) {
                    sum = sum.add(item.getPrice().multiply(new BigDecimal(item.getCount())));
                }
            }
            orderConfirmVO.setTotal(sum);
        }, executor).thenRunAsync(()-> {
            List<OrderItemVO> items = orderConfirmVO.getItems();
            List<Long> skuIds = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R hasStock = wmsFeignService.getHasStock(skuIds);
            List<SkuStockVO> data = hasStock.getData(new TypeReference<List<SkuStockVO>>() {});
            if (data != null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVO::getSkuId, SkuStockVO::getHasStock));
                orderConfirmVO.setStocks(map);
            }

        },executor);

        //查询用户积分
        Integer integration = memberRespVO.getIntegration();
        orderConfirmVO.setIntegration(integration);

        //防重令牌
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        orderConfirmVO.setOrderToken(token);

        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVO.getId(),token,30, TimeUnit.MINUTES);

        try {
            CompletableFuture.allOf(getAddressFuture, cartFuture).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


        return orderConfirmVO;
    }

    @Override
    @Transactional
    //2PC 二阶提交（XA Transactions）会造成大量的锁定资源
    //seata使用AT分布式事务，是二阶事务的变种，在第一阶段就把事务提交了，第二阶段如果需要回滚使用回滚日志进行反向补偿
    //以上两种不适合高并发，这里采用柔性事务-TCC事务补偿方案，可靠消息 + 最终一致性（异步确保型）
//    @GlobalTransactional
    public SubmitOrderResponseVO submitOrder(OrderSubmitVO vo) {
        submitVOThreadLocal.set(vo);
        SubmitOrderResponseVO responseVO = new SubmitOrderResponseVO();
        responseVO.setCode(0);
        MemberRespVO memberRespVO = LoginUserInterceptor.threadLocal.get();
        //验令牌 创建订单 验价格 锁库存

        //1、验令牌[令牌的对比和删除必须保证原子性]
        //返回0：表示对比失败，无删除操作  返回1：表示对比成功，删除1条数据
        String script = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        //原子验证令牌和删除令牌
        Long execute = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVO.getId()), orderToken);
        if (execute == 0) {
            //令牌验证失败- 设置错误码，前端返回订单确认页
            responseVO.setCode(-1);
            return responseVO;
        }else {
            //验证成功
            responseVO.setCode(0);
            //创建订单、订单项等信息
            OrderCreateTo order = createOrder();
            //验价，判断前端是否计算错误，导致后台计算的付款金额与前端订单显示的不一致
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            //忽略小数点后2位的差异，1.01 == 1.0123
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比成功 - 保存订单
                saveOrder(order);
                //锁定库存，有异常则回滚订单数据
                WareSkuLockVO lockVO = new WareSkuLockVO();
                lockVO.setOrderSn(order.getOrder().getOrderSn());

                List<OrderItemVO> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVO itemVO = new OrderItemVO();
                    itemVO.setSkuId(item.getSkuId());
                    itemVO.setCount(item.getSkuQuantity());
                    itemVO.setTitle(item.getSkuName());
                    return itemVO;
                }).collect(Collectors.toList());
                lockVO.setLocks(locks);
                R r = wmsFeignService.orderLockStock(lockVO);
                if (r.getCode() == 0) {
                    //锁定成功
                    responseVO.setOrder(order.getOrder());
                    //订单创建成功的消息发到MQ
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create",order.getOrder());
                    return responseVO;
                } else {
                    //库存不足 锁定失败
                    responseVO.setCode(3);
                    return responseVO;
                }

            } else {
                //金额对比失败
                responseVO.setCode(2);
                return responseVO;
            }
        }
    }

    @Override
    @Transactional
    @GlobalTransactional
    public void testST(Integer t) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setMemberId(1L);
        this.save(orderEntity);

        R r = wmsFeignService.test();
        if (t == 1) {
            throw new RuntimeException();
        }
    }

    @Override
    public void testMQ() {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setMemberId(1L);
        //给MQ发送消息
        rabbitTemplate.convertAndSend("order-event-exchange","order.create",orderEntity);

    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //查询当前这个订单的最新状态
        OrderEntity entity = this.getById(orderEntity.getId());
        if (entity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            //关单
            OrderEntity update = new OrderEntity();
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            update.setId(entity.getId());
            this.updateById(update);
            //补偿消息：防止关单期间卡顿，库存解锁已执行，但是订单还是新建状态而不做任何操作，导致库存永远无法解锁
            OrderTO orderTO = new OrderTO();
            BeanUtils.copyProperties(orderEntity,orderTO);

            //保证消息一定会发送出去，每一个消息都可以做好日志记录（给数据库保存每一个消息的详细信息）
            //定期扫描数据库将失败的消息重新发送
            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTO);
        }

    }

    @Override
    public PageUtils listWithItem(Map<String, Object> params) {
        MemberRespVO memberRespVO = LoginUserInterceptor.threadLocal.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVO.getId()).orderByDesc("id")
        );
        List<OrderEntity> list = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVO vo) {
        //保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);

        //修改订单的状态信息
        String trade_status = vo.getTrade_status();
        //支付宝返回以下状态表示支付成功
        if ("TRADE_SUCCESS".equals(trade_status) || "TRADE_FINISHED".equals(trade_status)) {
            this.baseMapper.updateOrderStatus(vo.getOut_trade_no(), OrderStatusEnum.PAYED.getCode());
        }

        return null;
    }

    @Override
    public void createSeckillOrder(SeckillOrderTO seckillOrderTO) {
        //保存秒杀订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTO.getOrderSn());
        orderEntity.setMemberId(seckillOrderTO.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        BigDecimal multiply = seckillOrderTO.getSeckillPrice().multiply(new BigDecimal(seckillOrderTO.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);
        //保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrderTO.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        orderItemEntity.setSkuQuantity(seckillOrderTO.getNum());
        //TODO 远程获取当前SKU详细信息进行设置。
        //...
        orderItemService.save(orderItemEntity);
    }

    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    //创建订单
    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();

        //1、生成订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(orderSn);
        //获取所有的订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        //计算价格、积分、成长值
        computePrice(orderEntity,orderItemEntities);
        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntities);

        return orderCreateTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = BigDecimal.ZERO;//总额
        BigDecimal coupon = BigDecimal.ZERO;//优惠券优惠
        BigDecimal integration = BigDecimal.ZERO;//积分优惠
        BigDecimal promotion = BigDecimal.ZERO;//打折优惠
        BigDecimal gift = BigDecimal.ZERO;//赠送积分
        BigDecimal growth = BigDecimal.ZERO;//成长值
        //订单的总而，叠加每一个订单项的总额信息
        for (OrderItemEntity entity : orderItemEntities) {
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth()));
        }
        //订单优惠相关
        orderEntity.setTotalAmount(total);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        //设置积分
        orderEntity.setIntegration(gift.intValue());
        //设置成长值
        orderEntity.setGrowth(growth.intValue());
        //未删除
        orderEntity.setDeleteStatus(0);


    }

    //构建订单
    private OrderEntity buildOrder(String orderSn) {
        MemberRespVO memberRespVO = LoginUserInterceptor.threadLocal.get();
        OrderEntity orderEntity = new OrderEntity();
        //订单号
        orderEntity.setOrderSn(orderSn);
        //会员ID
        orderEntity.setMemberId(memberRespVO.getId());
        //获取收获地址信息
        OrderSubmitVO orderSubmitVO = submitVOThreadLocal.get();
        R r = wmsFeignService.getFare(orderSubmitVO.getAddrId());
        FareVO fareVO = r.getData(new TypeReference<FareVO>() {});
        //设置运费信息
        orderEntity.setFreightAmount(fareVO.getFare());
        //设置收货人信息
        orderEntity.setReceiverCity(fareVO.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fareVO.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fareVO.getAddress().getName());
        orderEntity.setReceiverPhone(fareVO.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fareVO.getAddress().getPostCode());
        orderEntity.setReceiverProvince(fareVO.getAddress().getProvince());
        orderEntity.setReceiverRegion(fareVO.getAddress().getRegion());
        //设置订单状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        return orderEntity;
    }

    //构建所有订单项
    private List<OrderItemEntity> buildOrderItems(String orderSn){
        List<OrderItemVO> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems != null && !currentUserCartItems.isEmpty()) {
            List<OrderItemEntity> itemEntitys = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return itemEntitys;
        }
        return null;
    }

    //构建单个订单项
    private OrderItemEntity buildOrderItem(OrderItemVO cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //商品的spu信息
        R r = productFeignService.getSpuInfoBySkuId(cartItem.getSkuId());
        SpuInfoVO data = r.getData(new TypeReference<SpuInfoVO>(){});
        orderItemEntity.setSpuId(data.getId());
        orderItemEntity.setSpuBrand(data.getBrandId().toString());
        orderItemEntity.setSpuName(data.getSpuName());
        orderItemEntity.setCategoryId(data.getCatalogId());
        //商品的sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");//将集合以指定的字符串分隔
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        //优惠信息（不做）
        //积分信息(积分等于价钱)
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        //成长值
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        //订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);
        //价格=sku单价*数量-优惠价
        BigDecimal orign = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity()));
        orign = orign.subtract(orderItemEntity.getCouponAmount()).subtract(orderItemEntity.getPromotionAmount()).subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(orign);


        return orderItemEntity;
    }

}